package com.leyou.search.service.impl;

import com.leyou.common.pojo.PageResult;
import com.leyou.search.pojo.Goods;
import com.leyou.search.respository.GoodsRepository;
import com.leyou.search.service.SearchService;
import com.leyou.search.utils.SearchRequest;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private GoodsRepository goodsRepository;

    /**
     * 这的查询不是从数据库中查询,是从索引库中查询
     *
     * @param searchRequest
     * @return
     */
    @Override
    public PageResult<Goods> search(SearchRequest searchRequest){
        //查询条件对象
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        //这个key是前台开始搜索的时候带过来的参数,如果没有参数,就不开始查询.
        String key = searchRequest.getKey();
        if (!StringUtils.isNotBlank(key)){
            return null;
        }
        queryBuilder.withQuery(QueryBuilders.matchQuery("all",key).operator(Operator.AND));
        //分页查询,在springData中分页都是从0开始的
        queryBuilder.withPageable(PageRequest.of(searchRequest.getPage() - 1,searchRequest.getSize()));
        //开始查询
        Page<Goods> goodsPage = goodsRepository.search(queryBuilder.build());
        return new PageResult<Goods>(goodsPage.getTotalElements(),new Long(goodsPage.getTotalPages()),goodsPage.getContent());
    }
}
